# Customize this file, documentation can be found here:
# https://docs.fastlane.tools/actions/
# All available actions: https://docs.fastlane.tools/actions
# can also be listed using the `fastlane actions` command

# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`

# If you want to automatically update fastlane if a new version is available:
# update_fastlane

# This is the minimum version number required.
# Update this, if you use features of a newer version
fastlane_version "2.66.2"

require 'Fileutils.rb'

default_platform :android

platform :android do
  before_all do
    BUILD_INTERMEDIATES = "/var/tmp/build_intermediates/"
    GIT_BRANCH = git_branch
    S3_BASE_URL = "https://s3-us-west-2.amazonaws.com/viro-builds/"
  end

  def on_error(exception)
       slack(
           message: ":thunder_cloud_and_rain: Build Pipeline failed!",
           success: false,
           default_payloads: [], #Pass an empty array to suppress all the default payloads.
           payload: {
            "Git Repository:" =>  "react-viro/#{GIT_BRANCH}",
            "Fastlane Lane:" => ENV["FASTLANE_LANE_NAME"],
            "Detailed Logs:" => "<https://virobuilds.ngrok.io/blue/organizations/jenkins/react-viro/activity/|react-viro Pipeline>",
            "Exception:" => "```#{exception}```"
           },
           use_webhook_configured_username_and_icon: true
       )
  end

  lane :save_git_log do
    begin
      sh("echo \"\n\nreact-viro/#{GIT_BRANCH}\n\" >> #{BUILD_INTERMEDIATES}s3_artifacts/git_log.txt")
      sh("git log #{GIT_BRANCH} --no-walk >> #{BUILD_INTERMEDIATES}s3_artifacts/git_log.txt")
    rescue => exception
           on_error(exception)
    end
  end

  lane :gradle_clean_bridge do
    begin
      gradle(task: "clean")
      sh("rm ../viro_renderer/viro_renderer-release.aar") # just to make sure
    rescue => exception
           on_error(exception)
    end
  end
  
  lane :react_viro_bridge_aar do
    begin
      sh("cp #{BUILD_INTERMEDIATES}viroreact_aar/viro_renderer-release.aar ../viro_renderer/")
    rescue => exception
           on_error(exception)
    end
  end
  
  lane :upload_builds_and_slack do
    Dir.chdir("#{BUILD_INTERMEDIATES}s3_artifacts") do
     timestamp=Time.now.strftime('%Y-%m-%d_%H-%M-%S')
     virocore_filename=sh("basename /var/tmp/build_intermediates/s3_artifacts/virocore-release-v*.aar| tr -d '\n'")
     viroreact_filename=sh("basename /var/tmp/build_intermediates/s3_artifacts/react-viro-*.tgz| tr -d '\n'")
     gvr_test_filename="app-gvr-release.apk"
     ovr_test_filename="app-ovr-release.apk"
     git_log_filename="git_log.txt"
     sh("aws s3 sync . s3://viro-builds/#{timestamp}/")
     s3_base_url="s3://viro-builds/#{timestamp}"

     url_virocore = sh("aws s3 presign #{s3_base_url}/#{virocore_filename} --expires-in 86400")
     url_tgz = sh("aws s3 presign #{s3_base_url}/#{viroreact_filename} --expires-in 86400")
     url_gvr_apk = sh("aws s3 presign #{s3_base_url}/#{gvr_test_filename} --expires-in 86400")
     url_ovr_apk = sh("aws s3 presign #{s3_base_url}/#{ovr_test_filename} --expires-in 86400")
     url_gitlog = sh("aws s3 presign #{s3_base_url}/#{git_log_filename} --expires-in 86400")
     #slack wouldnt hyperlink for https urls
     replace="http"
     url_virocore=url_virocore.sub(/https/, 'http')
     url_tgz=url_tgz.sub(/https/, 'http')
     url_gvr_apk=url_gvr_apk.sub(/https/, 'http')
     url_ovr_apk=url_ovr_apk.sub(/https/, 'http')
     url_gitlog=url_gitlog.sub(/https/, 'http')
     git_log_contents=sh("cat #{git_log_filename}")
     slack(
           use_webhook_configured_username_and_icon: true,
           message: ":white_check_mark: Build Pipeline successfully completed and artifacts uploaded to S3.",
           success: true,
           payload: {
             "Build Date" => Time.new.to_s,
             "Built Commits" => "```#{git_log_contents}```",
           },
           default_payloads: [],
           attachment_properties: {
              fields: [
              {
                 title: "Virocore AAR",
                 value: "URL #{url_virocore}",
                 short: false
              },
              {
                 title: "ViroReact NPM TGZ",
                 value: "URL #{url_tgz}",
                 short: false
              },
              {
                 title: "ViroReact GVR Release Test (android)",
                 value: "URL #{url_gvr_apk}",
                 short: false
              },
              {
                 title: "ViroReact OVR Release Test",
                 value: "URL #{url_ovr_apk}",
                 short: false
              },
              {              
                title: "Git Log",
                value: "URL #{url_gitlog}>",
                short: false
              },
              {
                 title: "ViroReact GVR Release Test (ios)",
                 value: "Uploaded to :rocket:",
                 short: false
              }
           ]
          }
       )
    end
  end  
  after_all do |lane|
    # This block is called, only if the executed lane was successful

    # slack(
    #   message: "Successfully deployed new App Update."
    # )
  end

  error do |lane, exception|
    # slack(
    #   message: exception.message,
    #   success: false
    # )
  end
end

# More information about multiple platforms in fastlane: https://docs.fastlane.tools/advanced/#control-configuration-by-lane-and-by-platform
# All available actions: https://docs.fastlane.tools/actions

# fastlane reports which actions are used. No personal data is recorded.
# Learn more at https://docs.fastlane.tools/#metrics
